﻿Imports System.Web
Imports System.Web.Services
Imports System.Web.WebSockets
Imports System.Net.WebSockets

Public Class MyWebSocketServer
    Implements System.Web.IHttpHandler

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        '        context.Response.ContentType = "text/plain"
        '       context.Response.Write("Hello World!")
        If context.IsWebSocketRequest Then
            context.Response.Write("new connection made... " & context.Request.Url.ToString)

            context.AcceptWebSocketRequest(AddressOf MyWebSocket)

        Else
            context.Response.Write(context.Request.Url.ToString)
            context.Response.Write("no WebSocket call!!")
        End If
        

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property


    '    public async Task MyWebSocket(AspNetWebSocketContext context)
    ' {
    '        WebSocket socket = context.WebSocket;
    '        while (true)
    '        {
    '           ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);

    '           // Asynchronously wait for a message to arrive from a client
    '           WebSocketReceiveResult result = 
    '                   await socket.ReceiveAsync(buffer, CancellationToken.None);

    '           // If the socket is still open, echo the message back to the client
    '           if (socket.State == WebSocketState.Open)
    '           {
    '                   string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,
    '                           result.Count);
    '                   userMessage = "You sent: " + userMessage + " at " + 
    '                           DateTime.Now.ToLongTimeString();
    '                   buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));

    '                   // Asynchronously send a message to the client
    '                   await socket.SendAsync(buffer, WebSocketMessageType.Text,
    '                           true, CancellationToken.None);
    '           }
    '           else { break; }
    '        }
    '}

    Public Async Function MyWebSocket(ByVal context As AspNetWebSocketContext) As Threading.Tasks.Task
        Try
            Dim socket As WebSocket = context.WebSocket

            If socket.State = WebSocketState.Open Then
                Dim responsestring As String = "hallo"
                Dim outputbuffer As New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(responsestring))
                Await socket.SendAsync(outputbuffer, WebSocketMessageType.Text, True, Threading.CancellationToken.None)
            Else
                Debug.WriteLine("Feler...")
                HttpContext.Current.Response.Write("Fehler...")
            End If
        Catch ex As Exception
            Debug.WriteLine(ex.Message.ToString)
            HttpContext.Current.Response.Write("Fehler...")
        End Try




        'Dim buffer As ArraySegment(Of Byte) = New ArraySegment(Of Byte)(New Byte(1024) {})
        'Dim result As WebSocketReceiveResult = Await socket.ReceiveAsync(buffer, System.Threading.CancellationToken.None)

        'Dim sendmessage = "Hallo du da"
        'Dim retbuffer As New ArraySegment(Of Byte)(Encoding.UTF8.GetBytes(sendmessage))
        'Await socket.SendAsync(retbuffer, WebSocketMessageType.Text, True, System.Threading.CancellationToken.None)
    End Function

End Class